import subprocess
import sys
import os
import platform

def is_root():
    """检查当前用户是否具有 root 权限（仅在 Unix/Linux 系统中适用）"""
    return os.geteuid() == 0

def elevate_privileges():
    """如果当前用户不是 root，则尝试使用 sudo 提升权限"""
    if not is_root():
        print("This script needs to run with elevated privileges.")
        subprocess.run(['sudo', sys.executable] + sys.argv)
        exit(0)

def install_package(package_name, command):
    """
    安装指定的软件包。
    
    :param package_name: 要安装的软件包名称
    :param command: 用于安装软件包的命令列表
    """
    try:
        # 执行安装命令
        subprocess.run(command + [package_name], check=True)
        print(f"Package {package_name} installed successfully.")
    except subprocess.CalledProcessError as e:
        # 处理命令执行失败的情况
        print(f"Failed to install {package_name}. Error: {e}")
    except Exception as e:
        # 处理其他异常
        print(f"An unexpected error occurred: {e}")

def git_clone(repo_url, target_dir):
    """
    使用 git clone 命令克隆指定的仓库。
    
    :param repo_url: Git 仓库 URL
    :param target_dir: 克隆的目标目录
    """
    try:
        # 执行 git clone 命令
        subprocess.run(['git', 'clone', repo_url, target_dir], check=True)
        print(f"Repository cloned successfully into {target_dir}.")
    except subprocess.CalledProcessError as e:
        # 处理命令执行失败的情况
        print(f"Failed to clone repository. Error: {e}")
    except Exception as e:
        # 处理其他异常
        print(f"An unexpected error occurred: {e}")

def execute_docker_command(docker_command):
    """
    执行 Docker 命令。
    
    :param docker_command: Docker 命令列表
    """
    try:
        # 执行 Docker 命令
        subprocess.run(docker_command, check=True)
        print(f"Docker command executed successfully.")
    except subprocess.CalledProcessError as e:
        # 处理命令执行失败的情况
        print(f"Failed to execute Docker command. Error: {e}")
    except Exception as e:
        # 处理其他异常
        print(f"An unexpected error occurred: {e}")

def read_requirements_file(file_path):
    """
    从 requirements.txt 文件中读取所有需要安装的软件包。
    
    :param file_path: requirements.txt 文件路径
    :return: 包含所有软件包名称的列表
    """
    try:
        with open(file_path, 'r') as file:
            packages = file.read().splitlines()
        return packages
    except FileNotFoundError:
        print(f"The file {file_path} was not found.")
        return []
    except Exception as e:
        print(f"An error occurred while reading the file: {e}")
        return []

def main():
    # 检查命令行参数是否正确
    if len(sys.argv) < 2:
        print("Usage: python script.py requirements_file_path [repo_url] [target_dir] [docker_compose_yml_path]")
        return

    # 获取 requirements.txt 文件路径
    requirements_file_path = sys.argv[1]

    # 从 requirements.txt 文件中读取所有需要安装的软件包
    packages = read_requirements_file(requirements_file_path)

    # 检查是否有 Git 仓库需要克隆
    repo_url = None
    target_dir = None
    docker_compose_yml_path = None
    if len(sys.argv) > 2:
        repo_url = sys.argv[2]
        target_dir = sys.argv[3]
        docker_compose_yml_path = sys.argv[4]

    # 根据操作系统选择合适的安装命令
    system = platform.system()
    if system == 'Linux':
        # Linux 使用 apt (Debian 系列) 或其他包管理器
        if 'Ubuntu' in platform.platform() or 'Debian' in platform.platform():
            command = ['apt-get', 'install', '-y']
            elevate_privileges()  # 提升权限
            for package in packages:
                install_package(package, command)
            # 安装 Git
            install_package('git', command)
        elif 'CentOS' in platform.platform() or 'Fedora' in platform.platform():
            command = ['dnf', 'install', '-y']
            elevate_privileges()  # 提升权限
            for package in packages:
                install_package(package, command)
            # 安装 Git
            install_package('git', command)
        elif 'Arch' in platform.platform():
            command = ['pacman', '-S', '--noconfirm']
            elevate_privileges()  # 提升权限
            for package in packages:
                install_package(package, command)
            # 安装 Git
            install_package('git', command)
        else:
            print("Unsupported Linux distribution.")
    elif system == 'Windows':
        # Windows 使用 winget
        command = ['winget', 'install', '--id=']
        for package in packages:
            install_package(package, command)
        # 安装 Git
        install_package('Git.Git', command)
    elif system == 'Darwin':
        # macOS 使用 Homebrew
        command = ['brew', 'install']
        for package in packages:
            install_package(package, command)
        # 安装 Git
        install_package('git', command)
    else:
        print("Unsupported operating system.")

    # 如果有 Git 仓库需要克隆，则执行 git clone
    if repo_url and target_dir:
        git_clone(repo_url, target_dir)

    # 如果需要执行 Docker Compose 命令，则执行
    if docker_compose_yml_path:
        elevate_privileges()  # Docker 通常也需要 root 权限
        docker_compose_command = ['docker-compose', '-f', docker_compose_yml_path, 'up', '-d']
        execute_docker_command(docker_compose_command)

if __name__ == "__main__":
    main()